<template>
  <div class="pdf-word-container">
    <div class="pdf-word-card">
      <div class="card-header">
        <h2>PDF简历转换</h2>
        <p class="subtitle">上传PDF简历，一键生成规范化Word文档</p>
      </div>

      <div
        class="upload-area"
        :class="{ 'is-dragover': isDragover }"
        @dragover.prevent="handleDragover"
        @dragleave.prevent="isDragover = false"
        @drop.prevent="handleFileDrop"
        @click="handleAreaClick"
      >
        <input
          ref="fileInput"
          type="file"
          accept="application/pdf"
          class="file-input"
          @change="handleFileChange"
        />

        <template v-if="!selectedFile && !processing">
          <el-icon class="upload-icon"><Upload /></el-icon>
          <div class="upload-text">
            <p>拖拽PDF简历至此处或点击上传</p>
            <p class="upload-hint">支持单个PDF文件，最大20MB</p>
          </div>
        </template>

        <template v-else-if="selectedFile && !processing">
          <el-icon class="file-icon"><Document /></el-icon>
          <div class="file-info">
            <p class="file-name">{{ selectedFile.name }}</p>
            <p class="file-size">{{ formatFileSize(selectedFile.size) }}</p>
          </div>
          <div class="file-actions">
            <el-button type="primary" @click.stop="handleUpload">开始转换</el-button>
            <el-button @click.stop="resetFile">重新选择</el-button>
          </div>
        </template>

        <div v-if="processing" class="processing-status">
          <el-progress
            type="circle"
            :percentage="uploadProgress"
            :status="uploadProgress === 100 ? 'success' : ''"
          />
          <p class="progress-text">{{ progressText }}</p>
          <el-button
            v-if="uploadProgress === 100 && !result"
            type="danger"
            @click.stop="cancelProcessing"
          >
            取消处理
          </el-button>
        </div>
      </div>

      <div v-if="result" class="result-area">
        <div class="result-header">
          <el-icon class="success-icon"><SuccessFilled /></el-icon>
          <span>简历转换提交成功！</span>
        </div>
        <!-- <el-button type="primary" class="download-btn" @click="downloadResult">
          <el-icon><Download /></el-icon>
          下载Word文档
        </el-button> -->
        <el-button @click="resetAll">继续转换</el-button>
      </div>

      <div class="card-footer">
        <p>提示：转换过程需要一定时间，请耐心等待。转换后的文档会自动进行格式优化。</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, defineProps } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Download, SuccessFilled, Upload } from '@element-plus/icons-vue'
import { getAccessToken } from '@/utils/auth'
import { config } from '@/config/axios/config'

// 定义Props接口
interface PdfConverterProps {
  apiUrl: string // API端点路径
  title?: string // 可选标题
  subtitle?: string // 可选副标题
}

// 定义组件属性
const props = withDefaults(defineProps<PdfConverterProps>(), {
  apiUrl: '/ai/chat/message/transfer', // 默认API路径
  title: 'PDF简历转换',
  subtitle: '上传PDF简历，一键生成规范化Word文档'
})

const fileInput = ref<HTMLInputElement | null>(null)
const selectedFile = ref<File | null>(null)
const isDragover = ref(false)
const processing = ref(false)
const uploadProgress = ref(0)
const result = ref<Blob | null>(null)
const controller = ref<AbortController | null>(null)

// 计算属性：进度文本
const progressText = computed(() => {
  if (uploadProgress.value < 100) {
    return `上传中 ${uploadProgress.value}%`
  }
  return '处理中，请稍候...'
})

// 点击上传区域
const handleAreaClick = () => {
  if (!processing.value && !result.value) {
    fileInput.value?.click()
  }
}

// 处理拖拽事件
const handleDragover = () => {
  isDragover.value = true
}

// 处理文件拖放
const handleFileDrop = (e: DragEvent) => {
  isDragover.value = false
  const files = e.dataTransfer?.files
  if (files && files.length > 0) {
    validateAndSetFile(files[0])
  }
}

// 处理文件选择
const handleFileChange = (e: Event) => {
  const input = e.target as HTMLInputElement
  if (input.files && input.files.length > 0) {
    validateAndSetFile(input.files[0])
  }
}

// 验证并设置文件
const validateAndSetFile = (file: File) => {
  if (!file.type.includes('pdf')) {
    ElMessage.error('只支持PDF文件')
    return
  }

  // 限制文件大小为20MB
  if (file.size > 20 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过20MB')
    return
  }

  selectedFile.value = file
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(2) + ' MB'
  }
}

// 重置文件选择
const resetFile = () => {
  selectedFile.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 重置所有状态
const resetAll = () => {
  resetFile()
  result.value = null
  uploadProgress.value = 0
  processing.value = false
}

// 取消处理
const cancelProcessing = async () => {
  try {
    const confirmed = await ElMessageBox.confirm('确定要取消处理吗？当前处理进度将丢失。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (confirmed) {
      controller.value?.abort()
      resetAll()
    }
  } catch {
    // 用户取消弹窗
  }
}

// 下载结果
const downloadResult = () => {
  if (!result.value) return

  // 创建下载链接
  const url = URL.createObjectURL(result.value)
  const a = document.createElement('a')
  a.href = url

  // 设置文件名 - 从原文件名推断或使用默认名
  let fileName = selectedFile.value?.name || 'resume'
  fileName = fileName.replace(/\.pdf$/i, '') + '.docx'
  a.download = fileName

  // 触发下载
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 上传文件并处理
const handleUpload = async () => {
  if (!selectedFile.value) return

  processing.value = true
  uploadProgress.value = 0
  controller.value = new AbortController()

  try {
    // 创建FormData
    const formData = new FormData()
    formData.append('file', selectedFile.value)

    // 创建XHR请求，直接处理二进制响应和上传进度
    const xhr = new XMLHttpRequest()
    xhr.open('POST', `${config.base_url}${props.apiUrl}`, true)
    // 返回结果是 {
    // "code": 0,
    // "data": true,
    // "msg": ""
    // }
    // 所以设置响应类型为json，如何拿到数据呢
    xhr.responseType = 'json'
    // xhr.responseType = 'blob' // 设置响应类型为blob，确保能正确处理二进制文件

    // 添加授权头
    const token = getAccessToken()
    if (token) {
      xhr.setRequestHeader('Authorization', `Bearer ${token}`)
    }

    // 处理进度
    xhr.upload.onprogress = (e) => {
      if (e.lengthComputable) {
        // 只更新到99%，留1%给后端处理
        const percent = Math.min(99, Math.round((e.loaded / e.total) * 100))
        uploadProgress.value = percent
      }
    }

    // 处理完成
    xhr.onload = function () {
      if (xhr.status === 200) {
        // 完成上传和处理，设置进度为100%
        uploadProgress.value = 100

        // 检查响应内容
        const res = xhr.response
        if (res.code === 0 && res.data) {
          result.value = res.data
          ElMessage.success('简历转换成功')
        } else {
          ElMessage.error('转换失败：无法获取文件内容')
          processing.value = false
        }
        // if (blob && blob.size > 0) {
        //   // 保存结果用于下载
        //   result.value = blob
        //   ElMessage.success('简历转换成功')
        //   // 自动下载文件
        //   downloadResult()
        // } else {
        //   ElMessage.error('转换失败：无法获取文件内容')
        //   processing.value = false
        // }
      } else {
        ElMessage.error(`转换失败：服务器返回错误码 ${xhr.status}`)
        processing.value = false
      }
    }

    // 处理错误
    xhr.onerror = function () {
      ElMessage.error('转换失败：网络错误')
      processing.value = false
    }

    // 处理超时
    xhr.ontimeout = function () {
      ElMessage.error('转换失败：请求超时')
      processing.value = false
    }

    // 处理取消
    xhr.onabort = function () {
      ElMessage.info('已取消处理')
      processing.value = false
    }

    // 发送请求
    xhr.send(formData)
  } catch (error) {
    ElMessage.error('转换过程出错')
    processing.value = false
  }
}
</script>

<style scoped>
.pdf-word-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 150px);
  padding: 20px;
}

.pdf-word-card {
  width: 100%;
  max-width: 700px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
}

.card-header {
  margin-bottom: 30px;
  text-align: center;
}

.card-header h2 {
  margin-bottom: 8px;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
}

.upload-area {
  position: relative;
  display: flex;
  min-height: 250px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  transition: all 0.3s;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-area.is-dragover {
  background-color: rgb(64 158 255 / 5%);
  border-color: #409eff;
}

.file-input {
  display: none;
}

.upload-icon,
.file-icon {
  margin-bottom: 16px;
  font-size: 40px;
  color: #909399;
}

.upload-text p {
  margin: 0;
  font-size: 16px;
  color: #606266;
}

.upload-hint {
  margin-top: 8px !important;
  font-size: 12px !important;
  color: #909399 !important;
}

.file-info {
  margin-bottom: 16px;
}

.file-name {
  margin: 0 0 4px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.file-size {
  margin: 0;
  font-size: 13px;
  color: #909399;
}

.file-actions {
  margin-top: 20px;
}

.processing-status {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.progress-text {
  margin: 12px 0;
  font-size: 14px;
  color: #606266;
}

.result-area {
  padding: 20px;
  margin-top: 30px;
  text-align: center;
  background-color: #f0f9eb;
  border-radius: 8px;
}

.result-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.success-icon {
  margin-right: 8px;
  font-size: 22px;
  color: #67c23a;
}

.download-btn {
  margin-right: 10px;
}

.card-footer {
  padding-top: 20px;
  margin-top: 30px;
  font-size: 12px;
  color: #909399;
  text-align: center;
  border-top: 1px solid #ebeef5;
}
</style>
